﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using KPIS.GERP.GHRMS.APP.Classes;
using KPIS.GERP.GHRMS.APP.TimeAttentsService;
using KPIS.GERP.GHRMS.BLL;
using KPIS.GERP.GHRMS.IBLL;
using KPIS.GERP.GHRMS.MODEL;
using Telerik.Web.UI;

namespace KPIS.GERP.GHRMS.APP.App_UI.Forms
{
    public partial class PS_TimeAttMonthlyDetails : System.Web.UI.Page
    {
        private SsMng ssMng = new SsMng();
        private IEmployeeTypeBLL empTypeBLL = new EmployeeTypeBLL();
        private IEmployeeBLL empBLL = new EmployeeBLL();
        private ITimeAttMonthlyBLL TimeAttMon = new TimeAttMonthlyBLL();
        private ITimeAttendantsBLL TimeAtt = new TimeAttendantsBLL();
        private IAbsenceBLL AbsenceInfo = new AbsenceBLL();
        private IAbsenceRuleBLL AbsenceRuleInfo = new AbsenceRuleBLL();
        private IJobSiteBLL jsBLL = new JobSiteBLL();
        private TimeAttentsServiceClient taService = new TimeAttentsServiceClient();
        private Main main = new Main();
        private const int ItemsPerRequest = 10;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                bindEmpType(main.ConvertNullInt(Request["EmpTypeSeq"]));
                bindYear(main.ConvertDefaultInt(Request["ThYear"]));
                bindMonth(main.ConvertDefaultInt(Request["Month"]));
                bindJobSite(main.ConvertNullInt(Request["JobSiteSeq"]));
                bindHistoryCalculated();
            }
        }

        private void bindHistoryCalculated()
        {
            var empDataDt = empBLL.LoadEmployees(null, "", true, "").Tables[0];
            Dictionary<int, string> empData = new Dictionary<int, string>();
            foreach (DataRow dr in empDataDt.Rows)
            {
                empData.Add(Convert.ToInt32(dr["EMP_SEQ"]), Convert.ToString(dr["FULL_NAME"]));
            }
            var empTypeData = empTypeBLL.ListEmployeeTypes(null);
            var jobSiteDataDt = jsBLL.ListJobSite("");
            List<JobSiteInfo> jobSiteData = new List<JobSiteInfo>();
            foreach (DataRow dr in jobSiteDataDt.Rows)
            {
                jobSiteData.Add(new JobSiteInfo { Name = Convert.ToString(dr["job_site_name"]), Sequence = Convert.ToInt32(dr["job_site_seq"]) });
            }

            jobSiteData = jobSiteData.OrderBy(o => o.Sequence).ToList();

            var data = taService.ListPsTimeAttCalAudit().OrderByDescending(o => o.ReCalculateWhen);
            DataTable dt = new DataTable();
            dt.Columns.Add("TimeAttCalAuditId");
            dt.Columns.Add("WorkingYear");
            dt.Columns.Add("WorkingMonth");
            dt.Columns.Add("Success");
            dt.Columns.Add("Remarks");
            dt.Columns.Add("FilteredJobSiteName");
            dt.Columns.Add("FilteredEmployeeType");
            dt.Columns.Add("ReCalculateWhen");
            dt.Columns.Add("ReCalculatedByEmployeeFullName");
            foreach (var d in data)
            {
                var jobSite = (jobSiteData.FirstOrDefault(o => o.Sequence == d.FilteredJobSiteId) ?? new JobSiteInfo { Name = "ไม่ได้เลือก" });
                var empType = (empTypeData.FirstOrDefault(o => o.Sequence == d.FilteredEmpTypeId) ?? new EmployeeTypeInfo { Name = "ไม่ได้เลือก" });
                var emp = (empData.FirstOrDefault(o => o.Key == d.ReCalculateByEmpId));
                DataRow dr = dt.NewRow();
                dr[0] = d.TimeAttCalAuditId;
                dr[1] = d.WorkingYear + 543;
                dr[2] = d.WorkingMonth;
                dr[3] = d.Success ? "สำเร็จ" : "ไม่สำเร็จ";
                dr[4] = d.Remarks;
                dr[5] = jobSite.Name;
                dr[6] = empType.Name;
                dr[7] = d.ReCalculateWhen.ToString("dd/MM/yyyy HH:mm");
                dr[8] = emp.Value;
                dt.Rows.Add(dr);
            }
            RadGrid1.DataSource = dt;
            RadGrid1.DataBind();
        }

        private void bindJobSite(int? jobSiteSeq = null)
        {
            if (jobSiteSeq == null) return;

            DataTable dt = jsBLL.LoadJobSiteSearchText(SystemInfo._JobsiteInternal, "", "").Tables[0];
            DataRow firstRow = dt.NewRow();
            firstRow["JOB_SITE_SEQ"] = "";
            firstRow["JOB_SITE_NAME"] = "คำนวนทั้งหมด";
            dt.Rows.InsertAt(firstRow, 0);

            for (int i = 0; i < dt.Rows.Count; i++)
            {
                string eachJobSiteName = dt.Rows[i]["JOB_SITE_NAME"].ToString();
                int eachJobSiteSeq = Convert.ToInt32(dt.Rows[i]["JOB_SITE_SEQ"]);
                if (eachJobSiteSeq == jobSiteSeq)
                {
                    cmbJobSite.Items.Add(new RadComboBoxItem(eachJobSiteName, "" + eachJobSiteSeq));

                    TableRow tr = new TableRow();
                    TableCell tdFieldName = new TableCell();
                    Label lblFieldName = new Label();
                    lblFieldName.Text = eachJobSiteName;
                    tdFieldName.Width = Unit.Pixel(150);
                    tdFieldName.Controls.Add(lblFieldName);
                    tr.Cells.Add(tdFieldName);

                    ((Table)cmbJobSite.Items[cmbJobSite.Items.Count - 1].FindControl("tableJobSite")).Controls.Add(tr);
                    return;
                }
            }

            cmbJobSite.SelectedValue = "";
        }

        private void bindEmpType(int? empTypeSeq = null)
        {
            IList<EmployeeTypeInfo> infoList = empTypeBLL.ListEmployeeTypes();
            infoList.Insert(0, new EmployeeTypeInfo
            {
                Name = "(คำนวนทั้งหมด)",
                RecordStatus = "U",
                Sequence = 0
            });
            ddlEmployeeType.DataSource = infoList;
            ddlEmployeeType.DataBind();

            if (empTypeSeq.HasValue)
            {
                var item = ddlEmployeeType.FindItemByValue("" + empTypeSeq);
                if (item != null)
                {
                    ddlEmployeeType.SelectedValue = "" + empTypeSeq;
                }
            }

            ddlEmployeeType.SelectedValue = "0";
        }

        private void bindYear(int thYear)
        {
            DataTable dt = new DataTable();
            dt.Columns.Add("Name", typeof(string));
            for (int i = 2500; i <= 2600; i++)
            {
                dt.Rows.Add(Convert.ToString(i));
            }
            cmbFilterYear.DataSource = dt;
            cmbFilterYear.DataBind();
            cmbFilterYear.SelectedValue = Convert.ToString(thYear);
        }

        private void bindMonth(int month)
        {
            ddlMonth.SelectedValue = Convert.ToString(month);
        }

        protected void cmbJobSite_ItemsRequested(object o, RadComboBoxItemsRequestedEventArgs e)
        {
            DataSet ds = jsBLL.LoadJobSiteSearchText(SystemInfo._JobsiteInternal, "", e.Text);
            DataTable dt = ds.Tables[0];

            int itemOffset = e.NumberOfItems;
            int endOffset = Math.Min(itemOffset + ItemsPerRequest, dt.Rows.Count);
            e.EndOfItems = (endOffset == dt.Rows.Count);
            int j = 0;
            for (int i = itemOffset; i < endOffset; i++)
            {
                cmbJobSite.Items.Add(new RadComboBoxItem(dt.Rows[i]["JOB_SITE_NAME"].ToString(), dt.Rows[i]["JOB_SITE_SEQ"].ToString()));

                TableRow tr = new TableRow();
                TableCell tdFieldName = new TableCell();
                Label lblFieldName = new Label();
                lblFieldName.Text = dt.Rows[i]["JOB_SITE_NAME"].ToString();
                tdFieldName.Width = Unit.Pixel(150);
                tdFieldName.Controls.Add(lblFieldName);
                tr.Cells.Add(tdFieldName);

                ((Table)cmbJobSite.Items[j].FindControl("tableJobSite")).Controls.Add(tr);
                j++;
            }
            e.Message = GetStatusMessage(endOffset, dt.Rows.Count);
        }

        private static string GetStatusMessage(int offset, int total)
        {
            if (total <= 0)
                return "ไม่มีข้อมูล";

            return String.Format("รายการที่ <b>1</b>-<b>{0}</b> จากทั้งหมด <b>{1}</b> รายการ", offset, total);
        }

        protected void btnAutoCal_Click(object sender, EventArgs e)
        {
            //binding data to grid

            taService.CalculateTimeAttendanceMonthly(Model.DbYear, Model.Month, Model.JobSiteSeq, Model.EmpTypeSeq, ssMng.EmpSeqI);
        }

        protected void btnShow_Click(object sender, EventArgs e)
        {
            var empDataDt = empBLL.LoadEmployees(null, "", true, "").Tables[0];
            Dictionary<int, string> empData = new Dictionary<int, string>();
            foreach (DataRow dr in empDataDt.Rows)
            {
                empData.Add(Convert.ToInt32(dr["EMP_SEQ"]), Convert.ToString(dr["FULL_NAME"]));
            }
            var data = taService.ListPsTimeAttendanceMonthlies();

            if (Model.EmpTypeSeq.HasValue || Model.JobSiteSeq.HasValue)
            {
                var empDataDt2 = empBLL.LoadEmployees(null, Model.EmpTypeSeq.ToString(), null, Model.JobSiteSeq, true, "").Tables[0];
                Dictionary<int, string> empData2 = new Dictionary<int, string>();
                foreach (DataRow dr in empDataDt2.Rows)
                {
                    empData2.Add(Convert.ToInt32(dr["EMP_SEQ"]), Convert.ToString(dr["FULL_NAME"]));
                }
                data = data.Where(o => (from kv in empData2 select kv.Key).ToArray().Contains(main.ConvertDefaultInt(o.EmpId))).ToArray();
            }
            data = data.Where(o => o.WorkingYear == Model.DbYear && o.WorkingMonth == Model.Month).ToArray();

            DataTable dt = new DataTable();
            dt.Columns.Add("TimeAttMonthId");
            dt.Columns.Add("EmpId");
            dt.Columns.Add("WorkingMonth");
            dt.Columns.Add("WorkingYear");
            dt.Columns.Add("PlanWorkingDayCount");

            dt.Columns.Add("ActualWorkingDayCount");
            dt.Columns.Add("ValidAbsenceDayCount");
            dt.Columns.Add("InvalidAbsenceDayCount");
            dt.Columns.Add("LateDayCount");
            dt.Columns.Add("Remarks");

            dt.Columns.Add("RecordStatus");
            dt.Columns.Add("CreatedBy");
            dt.Columns.Add("CreatedWhen");
            dt.Columns.Add("UpdatedBy");
            dt.Columns.Add("UpdatedWhen");

            dt.Columns.Add("EmpFullName");
            dt.Columns.Add("NotWorkingDayCount");

            foreach (var d in data)
            {
                var emp = (empData.FirstOrDefault(o => o.Key == d.EmpId));
                DataRow dr = dt.NewRow();
                int i = 0;
                dr[i++] = d.TimeAttMonthId;
                dr[i++] = d.EmpId;
                dr[i++] = new DateTime(DateTime.Now.Year, d.WorkingMonth.Value, 1).ToString("MMMM");
                dr[i++] = d.WorkingYear + 543;
                dr[i++] = d.PlanWorkingDayCount.Value.ToString("0.# วัน");

                dr[i++] = d.ActualWorkingDayCount.Value.ToString("0.# วัน");
                dr[i++] = d.ValidAbsenceDayCount.Value.ToString("0.# วัน");
                dr[i++] = d.InvalidAbsenceDayCount.Value.ToString("0.# วัน");
                dr[i++] = d.LateDayCount.Value.ToString("0.# วัน");
                dr[i++] = d.Remarks;

                dr[i++] = d.RecordStatus;
                dr[i++] = d.CreatedBy;
                dr[i++] = d.CreatedWhen;
                dr[i++] = d.UpdatedBy;
                dr[i++] = d.UpdatedWhen;

                dr[i++] = emp.Value;
                dr[i++] = ((d.PlanWorkingDayCount ?? 0) - (d.ActualWorkingDayCount ?? 0) - (d.ValidAbsenceDayCount ?? 0)).ToString("0.# วัน");

                dt.Rows.Add(dr);
            }
            RadGrid2.DataSource = dt;
            RadGrid2.DataBind();
        }

        public FilterModel Model
        {
            get
            {
                var model = new FilterModel
                {
                    EmpTypeSeq = main.ConvertNullIntMakeZeroAsNull(ddlEmployeeType.SelectedValue),
                    JobSiteSeq = main.ConvertNullIntMakeZeroAsNull(main.ConvertNullIntMakeZeroAsNull(cmbJobSite.SelectedValue) == null ? SystemInfo._JobsiteInternal : cmbJobSite.SelectedValue),
                    DbYear = main.ConvertDefaultInt(cmbFilterYear.SelectedValue) - 543
                };
                if (model.EmpTypeSeq == 0)
                {
                    model.EmpTypeSeq = null;
                }
                if (model.JobSiteSeq == 0)
                {
                    model.JobSiteSeq = null;
                }
                int month = main.ConvertDefaultInt(ddlMonth.SelectedValue);
                if (month == 0) throw new Exception("ต้องเลือกเดือน");

                model.Month = month;
                return model;
            }
        }

        public class FilterModel
        {
            public int? EmpTypeSeq { get; set; }
            public int? JobSiteSeq { get; set; }
            public int DbYear { get; set; }
            public int Month { get; set; }
        }
    }
}